package daemon

import (
	"context"
	"github.com/sirupsen/logrus"
	"golang.org/x/sync/errgroup"
	"miao-wails/backed/app/dao"
	"miao-wails/backed/app/service"
	"miao-wails/backed/structs/base"
	"miao-wails/backed/structs/idp"
	"time"
)

type daemon struct {
	exitFunc  context.CancelFunc
	config    *base.AppConf
	idpConfig idp.Config
}

func NewDaemon(config *base.AppConf) *daemon {
	return &daemon{
		config: config,
	}
}

func (d *daemon) Run(ctx context.Context) {
	var (
		g errgroup.Group
	)
	ctx, cancelFunc := context.WithCancel(ctx)
	d.exitFunc = cancelFunc
	dao.InitDB()
	dao.InitIdpDb()
	g.Go(func() error {
		err := StartMediaServer(d.config.HttpPort, d.config.DataDir)
		if err != nil {
			logrus.Errorf("StartMediaServer exit,err:[%s]", err.Error())
		}
		return err
	})
	// 周期性扫描本地策略
	g.Go(func() error {
		ticker := time.NewTicker(time.Duration(60) * time.Second)
		defer ticker.Stop()
		var lastTime = time.Now().Unix()
		for range ticker.C {
			go func() {
				if (time.Now().Unix() - lastTime) > int64(d.idpConfig.HttpEcho) {
					err := service.IdpServ.UploadLogs()
					if err != nil {
						logrus.Errorf("GetNotUploadedLogs err:[%s]", err.Error())
						return
					}
					lastTime = time.Now().Unix()
				}
			}()
		}
		return nil
	})
	g.Go(func() error {
		defer func() {
			logrus.Debug("优雅关闭,协程-已退出")
			cancelFunc()
		}()
		<-ctx.Done()
		return nil //nolint
	})

	err := g.Wait()
	if err != nil {
		logrus.Debugf("shutting down the server: %v", err)
	}
}
